package com.azzaou.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

public class GlobalUtil {


	  /**
	   * Logger for this class
	   */
	  private static final Logger LOGGER = Logger.getLogger(GlobalUtil.class);
	  
	  /**
	   * 
	   * @param key
	   * @return
	   */
	  public static String md5(String key)
	  {
	    byte[] uniqueKey = key.getBytes();
	    byte[] hash = null;

	    try
	    {
	      /**
	       * We can chose an other algorithm : MD2, MD5, SHA-1, SHA-256, SHA-384,
	       * SHA-512
	       */
	      hash = MessageDigest.getInstance("SHA").digest(uniqueKey);
	    }
	    catch (NoSuchAlgorithmException e)
	    {
	      LOGGER.error(" Error No MD5 support in this VM", e);
	      throw new Error("No MD5 support in this VM");
	    }

	    StringBuffer hashString = new StringBuffer();
	    for (int i = 0; i < hash.length; ++i)
	    {
	      String hex = Integer.toHexString(hash[i]);
	      if (hex.length() == 1)
	      {
	        hashString.append('0');
	        hashString.append(hex.charAt(hex.length() - 1));
	      }
	      else
	      {
	        final int size = 2;
	        hashString.append(hex.substring(hex.length() - size));
	      }
	    }

	    return hashString.toString();
	  }
}
